package com.gosling.cloudspace.config;

//import com.soyoo.yooloan.framework.common.constant.CommonConstant;
//import com.soyoo.yooloan.framework.common.exception.enums.PrometheusTitleEnum;
//import com.soyoo.yooloan.framework.prometheus.core.handler.PrometheusUtil;
//import com.soyoo.yooloan.framework.prometheus.core.pojo.ExpBO;
import lombok.extern.slf4j.Slf4j;
        import org.springframework.beans.factory.InitializingBean;

        import javax.annotation.PreDestroy;

/**
 * nacos服务监听
 * @author lihonglin
 * @date 2024/4/1 9:28
 */
@Slf4j
//@Component
//@RefreshScope
public class NacosDiscoveryListener implements InitializingBean {
    String[] services = {
            "risk-server",
            "file-server",
            "pay-server",
            "user-server",
            "gateway-server",
            "auth-server",
            "business-server",
            "api-server",
            "backstage-server",
            "summary-server"};
//    @Value("${spring.cloud.nacos.discovery.server-addr}")
//    private String nacosUrl;
//    @Value("${spring.cloud.nacos.discovery.namespace}")
//    private String namespace;

    @PreDestroy
    public void preDestroy() {
        log.info("preDestroy....");
    }

    /**
     * 初始化监听服务上下线
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
//        MDC.put(CommonConstant.TRACE_ID, IdUtil.fastSimpleUUID());
//        Properties properties = System.getProperties();
//        properties.setProperty("serverAddr", nacosUrl);
//        properties.setProperty("namespace", namespace);
//        NamingService naming = NamingFactory.createNamingService(properties);
//        log.info("需要监控的服务数:{}", services.length);
//        for (String service : services) {
//            naming.subscribe(service, event -> {
//                MDC.put(CommonConstant.TRACE_ID, IdUtil.fastSimpleUUID());
//                List<Instance> instances = ((NamingEvent) event).getInstances();
//                String serviceName = ((NamingEvent) event).getServiceName();
//                if (instances.size() == 0) {
//                    log.info("服务【{}】未启动，加入监听列表", serviceName);
//                    //发送消息
//                    ExpBO exp = new ExpBO();
//                    exp.setUri("nacos-service-status-listener");
//                    exp.setMsg("服务【" + serviceName + "】已下线请检查");
//                    exp.setShowFlag(CommonConstant.NO);
//                    exp.setAtAll(CommonConstant.YES);
//                    exp.setReqData("nacosListener");
//                    exp.setTitleEnum(PrometheusTitleEnum.NACOS);
//                    PrometheusUtil.insert(exp);
//                } else {
//                    log.info("服务【{}】已启动", serviceName);
//                }
//            });
//        }
//        MDC.clear();
    }
}
